<?php

declare(strict_types=1);

namespace App\Controller\AdminApi;

use App\Constants\XZXResponseCode;
use App\Exception\XZXValidationException;
use App\Service\CommissionSalesTransService;
use App\Utils\CustomUtils;
use Hyperf\Contract\TranslatorInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\Arr;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use App\Middleware\AdminApi\AdminJWTAuthMiddleware;
use App\Middleware\AdminApi\NodeAccessMiddleware;

/**
 * Class CommissionSalesTransController
 * 销售提现审核
 *
 * @package App\Controller
 * @Controller(prefix="/admin/api/commissionSalesTrans")
 */
class CommissionSalesTransController extends AdminBaseController {
    /**
     * @Inject
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var CommissionSalesTransService
     */
    protected $CommissionSalesTransService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct (LoggerFactory $loggerFactory) {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    private function setLocale () {
        if ($this->request->header('locale') == 'en') {
            $this->translator->setLocale('en');
        }
    }

    /**
     * 列表
     * @PostMapping(path = "list")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function list (RequestInterface $request) {
        $this->setlocale();

        $validator = $this->validationFactory->make($request->all(), []);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = [
            'page'  => $request->post('page', 1),
            'limit' => $request->post('limit', 20),
        ];

        $search = $request->post('search', []);

        CustomUtils::xzxAddSearch($param, $search, 'handleStatus');

        return $this->CommissionSalesTransService->list($param);
    }

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function get (RequestInterface $request) {
        $this->setlocale();

        $validator = $this->validationFactory->make($request->all(), [
            'id' => 'required',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        return $this->CommissionSalesTransService->get($param);
    }

    /**
     * 添加
     * @PostMapping(path = "add")
     * @Middlewares({
     *     @Middleware(AdminJWTAuthMiddleware::class),
     *     @Middleware(NodeAccessMiddleware::class)
     * })
     */
    public function add (RequestInterface $request) {
        $this->setlocale();

        $validator = $this->validationFactory->make($request->all(), [
            'commissionId' => 'required',
            'transType'    => 'required',
            'code'         => 'required',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();

        if ($param['transType'] == 1 && (!isset($param['bankAccountName']) || empty($param['bankAccountName']) || !isset($param['bankAccountNo']) || empty($param['bankAccountNo']) || !isset($param['bankOpenBankNo']) || empty($param['bankOpenBankNo']))) {
            // 银行卡
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::BANK_ACCOUNT_INFO_REQUIRED));
        }
        else if ($param['transType'] == 2 && (!isset($param['mchEmail']) || empty($param['mchEmail']))) {
            // 转商户
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::MCH_EMAIL_REQUIRED));
        }

        $ext          = $this->request->getAttribute("ext");
        $param['uid'] = $ext['uid'];
        $param['createBy'] = $ext['createBy'];
        return $this->CommissionSalesTransService->add($param);
    }

    /**
     * 可选提现币种
     * @PostMapping(path = "currencyOptions")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function currencyOptions (RequestInterface $request) {
        $this->setlocale();

        $validator = $this->validationFactory->make($request->all(), [
            'transType' => 'required',
            'salesId'   => 'required',
            'sourceCurrency'   => 'required',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        return $this->CommissionSalesTransService->getCurrencyOptions($param);
    }

    /**
     * 提现订单初审
     * @PostMapping(path = "withdrawFirstReview")
     * @Middlewares({
     *     @Middleware(AdminJWTAuthMiddleware::class),
     *     @Middleware(NodeAccessMiddleware::class)
     * })
     */
    public function withdrawFirstReview (RequestInterface $request) {

        $ext = $this->request->getAttribute("ext");

        $validator = $this->validationFactory->make($request->all(), [
            'id'        => 'required',
            'isApprove' => 'required',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = [
            'id'          => $request->post('id'),
            'isApprove'   => !!$request->post('isApprove'),
            'remark'      => $request->post('remark', ''),
            'reviewLevel' => 1,
            'useApi'      => !!$request->post('useApi'),
            'channelId'   => $request->post('channelId'),
            'createBy'    => Arr::get($ext, 'createBy'),
        ];

        if (!Arr::get($ext, 'isSuperRole')) {
            $param['mchIdList'] = Arr::get($ext, 'mchIdList', []);
        }

        return $this->CommissionSalesTransService->withdrawFirstReview($param);
    }

    /**
     * 提现订单复审
     * @PostMapping(path = "withdrawSecondReview")
     * @Middlewares({
     *     @Middleware(AdminJWTAuthMiddleware::class),
     *     @Middleware(NodeAccessMiddleware::class)
     * })
     */
    public function withdrawSecondReview (RequestInterface $request) {

        $ext = $this->request->getAttribute("ext");

        $validator = $this->validationFactory->make($request->all(), [
            'id'        => 'required',
            'isApprove' => 'required',
        ]);

        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = [
            'id'          => $request->post('id'),
            'isApprove'   => !!$request->post('isApprove'),
            'remark'      => $request->post('remark', ''),
            'reviewLevel' => 2,
            'createBy'    => Arr::get($ext, 'createBy'),
        ];

        if (!Arr::get($ext, 'isSuperRole')) {
            $param['mchIdList'] = Arr::get($ext, 'mchIdList', []);
        }

        return $this->CommissionSalesTransService->withdrawSecondReview($param);
    }


}
